﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Rotate : MonoBehaviour
{
	private Vector3 startFingerPos;//触摸起始位置
	private Vector3 nowFingerPos;//触摸结束位置
	private float startTime0, endTime0;//触摸起始/结束时间
	private float  startTime1,endTime1; //转速检测起始/结束时间
	private float xMoveDistance;//滑动距离
	private float slidSpeed;//滑动速度
	private float rotateSpeed = 0;//转速

	public Rigidbody2D rb;
	public float SpeedPM;//速度参数
	public float AngularDrag;//角阻力
	public Text text;
	public Button ReSetButton,QuitButton;

    private void Start()
    {
		ReSetButton.onClick.AddListener(OnReset);
		QuitButton.onClick.AddListener(OnQuit);
    }
    private void Update()
    {
		JudgeFinger();
	}
    void JudgeFinger()
	{
		//没有触摸
		if (Input.touchCount <= 0 )
		{
			return;
		}

		//开始触摸，记录时间位置，重置角阻力
		if (Input.GetTouch(0).phase == TouchPhase.Began)
		{
			rb.angularDrag = 0.05f;
			startFingerPos = Input.GetTouch(0).position;
			startTime0 = Time.time;
		}

		nowFingerPos = Input.GetTouch(0).position;
		//结束触摸记录时间位置，改变角阻力来减速
		if ((Input.GetTouch(0).phase == TouchPhase.Stationary) || (Input.GetTouch(0).phase == TouchPhase.Ended))
		{

			startFingerPos = nowFingerPos;
			endTime0 = Time.time;
			rb.angularDrag = AngularDrag;
			return;
		}
		//触摸但是没有滑动
		if (startFingerPos == nowFingerPos)
		{
			return;
		}
		xMoveDistance = Mathf.Abs(nowFingerPos.x - startFingerPos.x);
		float totalTime = (float)System.Math.Round(endTime0 - startTime0, 2);
		slidSpeed =  Mathf.Round(xMoveDistance / totalTime)*SpeedPM;

        if (nowFingerPos.x - startFingerPos.x > 0)
        {
				rb.AddTorque(slidSpeed*Time.deltaTime); //逆时针旋转
        }
        else
        {
			rb.AddTorque(slidSpeed *-1* Time.deltaTime); //顺时针旋转
		}

	}


	//通过触发器检测转过的圈数和时间
    private void OnTriggerEnter2D(Collider2D collision)
    {
		startTime1 = Time.time;
		if (startTime1 - endTime1 > 0)
		{
			rotateSpeed = Mathf.Round(60 / (startTime1 - endTime1));
		}		
		endTime1 = startTime1;//本次触发作为起始下次触发作为结束时间
		text.text = rotateSpeed.ToString();	
    }

    void OnReset()//重置
    {
		AngularDrag = 0.05f;
		rotateSpeed = 0;
		text.text = rotateSpeed.ToString();
	}

	void OnQuit()//退出
	{
		Application.Quit();	
	}

}
